<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/6/19
 * Time: 15:13
 * Created by Created by Panxsoft.
 */
namespace App\Models\Customer;

use App\Models\Concerns\ScopeFilterable;
use App\Models\Panx\Product;
use App\Models\Store\Pack;
use App\Models\Url;
use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;

/**
 * Class Advert
 * @property int id
 * @property int advert_type_id
 * @property int redirectable_id
 * @property string name
 * @property int play_second
 * @property Pack|Product|Url|null redirectable
 * @package App\Models\Customer
 * @mixin Builder
 */
class Advert extends  Model
{
    use ScopeFilterable,
        Bosable;

    protected $table = 'adverts';

    protected $guarded = [];

    protected $key_bos_key_prefix = 'adverts/';

    public $bos_columns = ['content_key'];

    protected $casts = [
        'advert_type_id'  => 'int',
        'play_second'     => 'int',
        'redirectable_id' => 'int',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function deviceAccounts()
    {
        return $this->belongsToMany(DeviceAccount::class,'advert_pivot_device_account','advert_id','device_account_id');
    }

    public function advertType()
    {
        return $this->belongsTo(AdvertType::class,'advert_type_id','id');
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class,'customer_id','id');
    }

    /**
     * @return mixed|null
     */
    public function getContentKeyAttribute()
    {
        if (!$this->attributes['content_key']) return null;

        return $this->getStaticUrl($this->attributes['content_key']);
    }

    /**
     * @param $content_key
     * @throws \Exception
     */
    public function setContentKeyAttribute($content_key)
    {
        if (is_file($content_key)) {
            $this->attributes['content_key'] = $this->uploadPostFile($content_key, $this->key_bos_key_prefix);
        }else{
            $this->attributes['content_key'] = $content_key;
        }
    }

    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();

        /**
         * 监听bos清理事件
         */
        self::observe(BosCleanObserver::class);
    }

    /**
     * @used-by $redirectable
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function redirectable()
    {
        return $this->morphTo('redirectable');
    }

    public function destroyRedirectUrl(): void
    {
        if ($this->redirectable instanceof Url) {
            $this->redirectable->delete();
        }
    }
}